/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package modulos.agenda.vista;

import basedatos.ContactoBD;
import basedatos.OperacionesBD;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import modelo.Pyme;
import modulos.usuario.modelo.Usuario;
import modulos.agenda.modelo.Contacto;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import vista.frmPrincipal;
import vista.modelo.OperacionesVarias;

/**
 *
 * @author Edulima
 */
public class iFrmAgenda extends javax.swing.JInternalFrame {

    /**
     * Creates new form iFrmAgenda
     */
    private ArrayList<Contacto> listContactos;
    private Contacto mdfContacto;
    private DefaultTableModel tablaModelo = new DefaultTableModel();
    private int tipoUsuario = -1;
    private Usuario usuario;
//    CONSTANTES
    public static final int USUARIO_UNICO = 1;
    public static final int USUARIO_GENERAL = 2;

    public iFrmAgenda(int tipoUsuario) {
        tablaModelo.addColumn("N°");
        tablaModelo.addColumn("NOMBRE");
        tablaModelo.addColumn("APELLIDO");
        tablaModelo.addColumn("EMPRESA");
        tablaModelo.addColumn("TELEFONO");
        tablaModelo.addColumn("MOVIL");
        tablaModelo.addColumn("FAX");
        tablaModelo.addColumn("DIRECCION");
        tablaModelo.addColumn("MAIL");
        initComponents();
        usuario = (Usuario) frmPrincipal.UsuarioLogueado.get(0)[1];
        OperacionesVarias.cerrarVentanaEscape(this);
        this.tipoUsuario = tipoUsuario;
        switch (tipoUsuario) {
            case iFrmAgenda.USUARIO_GENERAL:
                listContactos = (ArrayList<Contacto>) ContactoBD.listarGeneral();
                break;
            case iFrmAgenda.USUARIO_UNICO:
                listContactos = (ArrayList<Contacto>) ContactoBD.listarPorUsuario(usuario);
        }
        listar();
        tblContactos.getColumnModel().getColumn(0).setPreferredWidth(40);
        tblContactos.getColumnModel().getColumn(1).setPreferredWidth(150);
        tblContactos.getColumnModel().getColumn(2).setPreferredWidth(150);
        tblContactos.getColumnModel().getColumn(3).setPreferredWidth(150);
        tblContactos.getColumnModel().getColumn(4).setPreferredWidth(100);
        tblContactos.getColumnModel().getColumn(5).setPreferredWidth(100);
        tblContactos.getColumnModel().getColumn(6).setPreferredWidth(100);
        tblContactos.getColumnModel().getColumn(7).setPreferredWidth(200);
        tblContactos.getColumnModel().getColumn(8).setPreferredWidth(200);
        tblContactos.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        this.setVisible(true);

    }

    private void listar() {
        refrescar();
        int aux = 0;
        for (Object cont : listContactos) {
            aux++;
            Contacto c = (Contacto) cont;
            Object[] fila = {
                aux,
                c.getNombre(),
                c.getApellido(),
                c.getEmpresa(),
                c.getTelefono(),
                c.getCelular(),
                c.getFax(),
                c.getDireccion(),
                c.getMail()
            };
            tablaModelo.addRow(fila);
        }
    }

    private void refrescar() {
        int c = tablaModelo.getRowCount();
        try {
            for (int i = 0; i < c; i++) {
                tablaModelo.removeRow(0);
            }

        } catch (Exception ex) {
            ex.getMessage();
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        btnNuevo = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnImprimir = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblContactos = new javax.swing.JTable();
        cmbCriterioBusqueda = new javax.swing.JComboBox();
        txtBusqueda1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();

        jPopupMenu1.setMinimumSize(new java.awt.Dimension(65, 50));

        jMenuItem2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/icono_editar.png"))); // NOI18N
        jMenuItem2.setText("Editar");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jPopupMenu1.add(jMenuItem2);

        jMenuItem3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/delete.png"))); // NOI18N
        jMenuItem3.setText("Eliminar");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jPopupMenu1.add(jMenuItem3);

        setClosable(true);
        setTitle("AGENDA TELEFONICA");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/agenda telefonica.png"))); // NOI18N
        setVisible(true);

        btnNuevo.setFont(new java.awt.Font("DejaVu Sans", 0, 13)); // NOI18N
        btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/add.png"))); // NOI18N
        btnNuevo.setText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnEditar.setFont(new java.awt.Font("DejaVu Sans", 0, 13)); // NOI18N
        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/icono_editar.png"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnEliminar.setFont(new java.awt.Font("DejaVu Sans", 0, 13)); // NOI18N
        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/delete.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnImprimir.setFont(new java.awt.Font("DejaVu Sans", 0, 13)); // NOI18N
        btnImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/printer1.png"))); // NOI18N
        btnImprimir.setText("Imprimir");
        btnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirActionPerformed(evt);
            }
        });

        btnSalir.setFont(new java.awt.Font("DejaVu Sans", 0, 13)); // NOI18N
        btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jpgs/agt_home.png"))); // NOI18N
        btnSalir.setText("Cerrar");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        tblContactos.setBackground(new java.awt.Color(209, 230, 239));
        tblContactos.setModel(tablaModelo);
        tblContactos.setComponentPopupMenu(jPopupMenu1);
        tblContactos.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jScrollPane1.setViewportView(tblContactos);

        cmbCriterioBusqueda.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Apellido", "Nombre", "Empresa" }));
        cmbCriterioBusqueda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbCriterioBusquedaActionPerformed(evt);
            }
        });

        txtBusqueda1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBusqueda1KeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtBusqueda1KeyTyped(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
        jLabel2.setText("Buscar:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(37, 37, 37)
                                .addComponent(jLabel2)
                                .addGap(6, 6, 6)
                                .addComponent(cmbCriterioBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtBusqueda1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(btnImprimir, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE)
                                    .addComponent(btnEliminar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(btnEditar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(btnNuevo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 913, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 14, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(45, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtBusqueda1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmbCriterioBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnNuevo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEditar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEliminar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnImprimir))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSalir))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        dispose();
    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        iFrmContacto frmAddContacto = new iFrmContacto(tipoUsuario);
        frmPrincipal.dskpPrincipal.add(frmAddContacto);
        OperacionesVarias.centrar(frmAddContacto);
        dispose();
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        if (tblContactos.getRowCount() > 0) {
            int aux = tblContactos.getSelectedRow();
            if (aux != -1) {
                mdfContacto = (Contacto) listContactos.get(aux);
                iFrmContacto frmAddContacto = new iFrmContacto(mdfContacto, tipoUsuario);
                frmPrincipal.dskpPrincipal.add(frmAddContacto);
                OperacionesVarias.centrar(frmAddContacto);
                dispose();

            } else {
                JOptionPane.showMessageDialog(this, "Seleccione el contacto que desea modificar ...", "Editar contacto", JOptionPane.WARNING_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "No ha registrado ningun Contacto para poder editar sus datos ...", "Editar contacto", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed

        if (tblContactos.getRowCount() > 0) {
            int aux = tblContactos.getSelectedRow();
            if (aux != -1) {
                mdfContacto = (Contacto) listContactos.get(aux);

                if (JOptionPane.showConfirmDialog(this, "Realmente quiere eliminar el contacto:\n" + mdfContacto.getNombre() + " " + mdfContacto.getApellido(), "Eliminar contacto", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                    try {
                        if (ContactoBD.eliminar(mdfContacto)) {
                            listContactos = (ArrayList<Contacto>) ContactoBD.listar("Contacto");
                            listar();
                            JOptionPane.showMessageDialog(this, "Contacto eliminado correctamente ...", "Eliminar contacto", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            JOptionPane.showMessageDialog(this, "El contacto no ha podido ser eliminado ...", "Eliminar contacto", JOptionPane.ERROR_MESSAGE);
                        }
                    } catch (Exception ex) {
                        Logger.getLogger(iFrmContacto.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "Seleccione el contacto que desea eliminar ...", "Eliminar contacto", JOptionPane.WARNING_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "No ha registrado ningun Contacto para poder eliminar ...", "Eliminar contacto", JOptionPane.WARNING_MESSAGE);
        }


    }//GEN-LAST:event_btnEliminarActionPerformed

    private void txtBusqueda1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBusqueda1KeyReleased
        switch (tipoUsuario) {
            case iFrmAgenda.USUARIO_GENERAL:
                if (cmbCriterioBusqueda.getSelectedItem().toString().trim().equalsIgnoreCase("Apellido")) {
                    listContactos = (ArrayList<Contacto>) ContactoBD.listarPrediccionGeneral("Apellido", txtBusqueda1.getText().trim());
                } else if (cmbCriterioBusqueda.getSelectedItem().toString().trim().equalsIgnoreCase("Nombre".trim())) {
                    listContactos = (ArrayList<Contacto>) ContactoBD.listarPrediccionGeneral("Nombre", txtBusqueda1.getText().trim());
                } else {
                    listContactos = (ArrayList<Contacto>) ContactoBD.listarPrediccionGeneral("Empresa", txtBusqueda1.getText().trim());
                }
                break;
            case iFrmAgenda.USUARIO_UNICO:
                if (cmbCriterioBusqueda.getSelectedItem().toString().trim().equalsIgnoreCase("Apellido")) {
                    listContactos = (ArrayList<Contacto>) ContactoBD.listarPrediccionPorUsuario("Apellido", txtBusqueda1.getText().trim(), usuario);
                } else if (cmbCriterioBusqueda.getSelectedItem().toString().trim().equalsIgnoreCase("Nombre".trim())) {
                    listContactos = (ArrayList<Contacto>) ContactoBD.listarPrediccionPorUsuario("Nombre", txtBusqueda1.getText().trim(), usuario);
                } else {
                    listContactos = (ArrayList<Contacto>) ContactoBD.listarPrediccionPorUsuario("Empresa", txtBusqueda1.getText().trim(), usuario);
                }
        }
        listar();
    }//GEN-LAST:event_txtBusqueda1KeyReleased

    private void txtBusqueda1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBusqueda1KeyTyped
        OperacionesVarias.ingresoSoloLetras(evt);
    }//GEN-LAST:event_txtBusqueda1KeyTyped

    private void cmbCriterioBusquedaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbCriterioBusquedaActionPerformed
        txtBusqueda1.setText("");
    }//GEN-LAST:event_cmbCriterioBusquedaActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        btnEditarActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        btnEliminarActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
        //Cargas Datos de Compañia
        ArrayList<Pyme> list = (ArrayList<Pyme>) OperacionesBD.listar("Pyme");
        Pyme pyme = null;
        if (!list.isEmpty()) {
            pyme = list.get(0);
        } else {
            pyme = new Pyme();
        }
        String urlImagen= getClass().getResource("/modulos/reportes/agenda/agenda.jpeg") + "";
        
        Map<String, Object> parametros = new HashMap<String, Object>();
        parametros.put("MEDICO", usuario + "");
        parametros.put("COMPANIA", pyme.getNombre());
        parametros.put("DIRECCION", pyme.getDireccion());
        parametros.put("TELEFONO", pyme.getTelefono());
        parametros.put("FAX", pyme.getFax());
        parametros.put("IMAGEN", urlImagen);

        try {

            JasperReport reporte = (JasperReport) JRLoader.loadObject(getClass().getResource("/modulos/reportes/agenda/Agenda.jasper"));
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, new JRBeanCollectionDataSource(listContactos));
            JasperViewer vista = new JasperViewer(jasperPrint, false);
            vista.setSize(this.getParent().getSize());
            vista.setVisible(true);
        } catch (JRException ex) {
            Logger.getLogger(iFrmAgenda.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_btnImprimirActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnImprimir;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JButton btnSalir;
    private javax.swing.JComboBox cmbCriterioBusqueda;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblContactos;
    private javax.swing.JTextField txtBusqueda1;
    // End of variables declaration//GEN-END:variables
}
